//
//  JCUserAccount.swift
//  weibo07777
//
//  Created by mac on 15/12/18.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

class JCUserAccount: NSObject ,NSCoding{
    
    /// 用户是否登录
    class var userLogin: Bool {
        get {
            return JCUserAccount.loadAccount() != nil
        }
    }
    
    var access_token : String?
    
    var uid : String?
    
    var expires_in :NSTimeInterval = 0{
        didSet{
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    var expiresDate : NSDate?
    
    /// 用户昵称
    var screen_name: String?
    
    /// 用户头像地址（大图），180×180像素,图片的网络地址
    var avatar_large: String?

    
    init(dic:[String: AnyObject]) {
        
        super.init()
        setValuesForKeysWithDictionary(dic)
        
    }
    // MARK :归档和解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_Token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large")as? String
    }
    
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_Token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large,forKey: "avatar_large")
    }
    
    
    // MARK: - 加载用户数据
    func loadUserInfo(finished: (error: NSError?) -> ()) {
        
        // 调用网络工具类的方法来加载用户信息,准备一个闭包
        JCNetWorkTool.sharedInstance.loadUserInfo { (result, error) -> () in
            // 判断是否又错误
            if error != nil || result == nil {
                //                print("获取用户数据有错误: \(error)")
                finished(error: error)
                return
            }
            
            // 能到下面来表示没有错误.
            // 解析服务器返回的数据,获取用户的名称和用户的头像地址
            self.screen_name = result!["screen_name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            print("loadUserInfo----\(self.avatar_large)")
            
            // 对象更新了内容.
            // 1.将最新的对象(self)赋值给属性 CZUserAccount.userAccount
            // userAccount是一个类属性,需要使用类名.属性名来访问
            JCUserAccount.userAccount = self
            // 2.将最新的对象保存到沙盒
            self.saveAccout()
            
            // 3.调用闭包告诉控制器获取用户数据成功了.
            finished(error: nil)
        }
    }
    
    
    // 保存路径 static 类方法也可以访问.对象方法访问需要使用类名.属性名
    static let plistPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! + "/account.plist"
    
    /// 保存账户信息到沙盒
    func saveAccout() {
        // 归档 当前类
        print("saveAccout\(self.avatar_large)")
        NSKeyedArchiver.archiveRootObject(self, toFile: JCUserAccount.plistPath)
        
    }
    
    static var userAccount : JCUserAccount?
    /// 加载账户信息
    class func loadAccount() -> JCUserAccount?{
        
        if userAccount == nil{
            
            print("沙盒加载账号")
            // 内存没有账号
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(plistPath) as? JCUserAccount
            print("----\(userAccount?.avatar_large)")
        }
            // 从内存加载
        // 2.判断内存中是否有用账户,有账户,判断时间是否过期
        if userAccount != nil && userAccount?.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
            // 有账户并且没有过期,是一个可用的账户
            print("内存加载账号")
            return userAccount
        }

            print("获取本地账号失败")
            return nil
    }
    
    /// 当KVC字典的key在模型中找不到对应的属性
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        return "access_token: \(access_token), expires_in:\(expires_in), uid = \(uid), expiresDate:\(expiresDate)"
    }

}
